<template>
  <!-- 模板部分无变化，保持校区选择下拉框正常渲染 -->
  <div class="login-container">
    <div class="login-card">
      <div class="login-header">
        <h2>学员注册</h2>
        <p>请填写基本信息完成注册</p>
      </div>

      <el-form
          :model="form"
          :rules="rules"
          ref="formRef"
          label-width="100px"
          class="register-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
              v-model="form.username"
              placeholder="4-16位字母数字组合"
              clearable
          />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
              v-model="form.password"
              type="password"
              placeholder="8-16位含字母、数字、特殊字符"
              show-password
          />
        </el-form-item>

        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
              v-model="form.confirmPassword"
              type="password"
              placeholder="再次输入密码"
              show-password
          />
        </el-form-item>

        <el-form-item label="真实姓名" prop="realName">
          <el-input
              v-model="form.realName"
              placeholder="请输入真实姓名（2-8个中文字符）"
              clearable
          />
        </el-form-item>

        <el-form-item label="手机号" prop="phone">
          <el-input
              v-model="form.phone"
              placeholder="请输入11位手机号"
              clearable
          />
        </el-form-item>

        <!-- 校区选择：v-model仍绑定form.campusId（前端用），提交时改字段名 -->
        <el-form-item label="所属校区" prop="campusId">
          <el-select
              v-model="form.campusId"
              placeholder="请选择校区"
              :loading="campusLoading"
              style="width: 100%"
              filterable
          >
            <el-option
                v-for="campus in campuses"
                :key="campus.id"
                :label="`${campus.name}（${campus.address || '暂无地址'}）`"
                :value="campus.id"
            >
            <span style="float: left; font-weight: 500;">{{ campus.name }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px;">
                {{ campus.address || '暂无地址' }}
              </span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="性别">
          <el-radio-group v-model="form.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="年龄" prop="age">
          <el-input-number
              v-model="form.age"
              :min="6"
              :max="80"
              placeholder="请输入年龄"
          />
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input
              v-model="form.email"
              placeholder="请输入正确邮箱格式（如xxx@example.com）"
              clearable
          />
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              @click="submitForm"
              :loading="loading"
          >
            立即注册
          </el-button>
          <el-button @click="goBack" style="margin-left: 10px;">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElInput, ElSelect, ElOption, ElInputNumber, ElRadioGroup, ElRadio, ElButton, ElForm } from 'element-plus'
import authApi from '@/api/auth'
import { getCampusList } from '@/api/campus'

const router = useRouter()

// 前端表单数据：campusId用于绑定下拉框（前端逻辑不变）
const form = reactive({
  username: '',
  password: '',
  confirmPassword: '',
  realName: '',
  phone: '',
  campusId: undefined, // 前端用，存储选中的校区ID（数字）
  gender: 'male',
  age: 18,
  email: ''
})

// 校区列表数据
const campuses = ref([])
const campusLoading = ref(true)
const formRef = ref()
const loading = ref(false)

// 表单验证规则（前端校验campusId，确保有值且是数字）
const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 20, message: '用户名长度需在 5-20 字符之间', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名仅支持字母、数字和下划线', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{8,}$/,
      message: '密码需包含字母、数字、特殊字符，且长度≥8', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    { validator: (rule, value, callback) => {
        if (value !== form.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      }, trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5]{2,8}$/, message: '真实姓名需为 2-8 个中文字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的11位手机号', trigger: 'blur' }
  ],
  campusId: [
    { required: true, message: '请选择校区', trigger: 'change' },
    { validator: (rule, value, callback) => {
        if (value === undefined || value === null || typeof value !== 'number') {
          callback(new Error('请选择有效的校区'))
        } else {
          callback()
        }
      }, trigger: 'change' }
  ],
  age: [
    { required: true, message: '请输入年龄', trigger: 'blur' },
    { type: 'number', min: 5, max: 100, message: '年龄需在 5-100 之间', trigger: 'blur' }
  ],
  email: [
    { pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
      message: '请输入正确的邮箱格式（如：xxx@example.com）', trigger: 'blur' }
  ]
})

// 页面加载获取校区列表（自动选中第一个）
onMounted(async () => {
  try {
    campusLoading.value = true
    const response = await getCampusList()
    if (response?.code === 200 && Array.isArray(response.data)) {
      campuses.value = response.data
      if (campuses.value.length > 0) {
        form.campusId = campuses.value[0].id
        console.log('页面加载自动选中校区ID（前端）：', form.campusId)
      } else {
        ElMessage.warning('暂无校区数据，请联系管理员添加后再注册')
      }
    } else {
      ElMessage.error(`获取校区失败：${response?.message || '接口返回格式异常'}`)
    }
  } catch (error) {
    ElMessage.error('网络错误：无法连接校区接口，请检查后端服务')
    console.error('校区列表加载异常：', error)
  } finally {
    campusLoading.value = false
  }
})

// 核心修复：提交参数时，将前端campusId映射为后端需要的字段名（如campus_id）
const submitForm = async () => {
  try {
    await formRef.value.validate()
    loading.value = true

    // 关键：字段名映射——前端campusId → 后端campus_id（根据后端实际字段名修改！）
    const submitData = {
      // 1. 复制其他前端字段（用户名、密码等，字段名需与后端匹配）
      username: form.username,
      password: form.password,
      realName: form.realName,
      phone: form.phone,
      gender: form.gender,
      age: form.age,
      email: form.email,
      userType: 'student',
      // 2. 核心映射：后端需要的校区ID字段名（此处用campus_id，若后端是schoolId则改为schoolId: form.campusId）
      campus_id: form.campusId, // 后端真实字段名！！！必须确认后修改
      // 3. 删除前端无用字段（确认密码、前端campusId）
      confirmPassword: undefined,
      campusId: undefined // 避免传递前端字段，防止后端混淆
    }

    // 打印关键日志：确认提交参数中包含后端需要的字段（如campus_id: 1）
    console.log('========================================')
    console.log('最终提交给后端的参数（重点看校区ID字段）：')
    console.log('后端字段名（campus_id）的值：', submitData.campus_id) // 应显示1（数字）
    console.log('后端字段名（campus_id）类型：', typeof submitData.campus_id) // 应显示number
    console.log('完整提交参数：', submitData)
    console.log('========================================')

    // 调用注册接口（传递映射后的参数）
    const res = await authApi.registerStudent(submitData)
    ElMessage.success(res.message || '注册成功')

    // 跳转到登录页
    setTimeout(() => {
      router.push('/')
    }, 1500)

  } catch (err) {
    if (err.name === 'Error' && err.message.includes('Validation failed')) {
      ElMessage.warning('请完善表单信息，确保所有必填项符合要求')
    } else if (err.message) {
      ElMessage.error(`注册失败：${err.message}`)
    } else if (err.response) {
      const errMsg = err.response.data?.message || '服务器异常，请稍后重试'
      ElMessage.error(`注册失败：${errMsg}`)
      console.error('后端错误详情：', err.response.data)
    } else {
      ElMessage.error('注册失败：未知错误，请联系管理员')
    }
  } finally {
    loading.value = false
  }
}

// 返回上一页
const goBack = () => {
  router.push('/register')
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

.login-card {
  width: 600px;
  padding: 30px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  color: #333;
  margin-bottom: 8px;
}

.login-header p {
  color: #666;
  font-size: 14px;
}

.register-form {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 22px;
}

.el-button + .el-button {
  margin-left: 12px;
}
</style>
